﻿using NewsReader.Helpers;
using NewsReader.Log;
using NewsReaderApp.ViewModels;
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;


namespace NewsReaderApp.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : NewsReaderPage
    {
        public MainPage()
        {
            this.InitializeComponent();
            SelectFeeds.ClickMode = ClickMode.Release;
            SelectFeeds.Click += HandleFeedSelectorClick;

            Loaded += (o, e) => hideSelectorStory.Begin();
        }


        private void HandleFeedSelectorClick(object sender, RoutedEventArgs e)
        {
            ShowFeedSelector();
        }

        private void ShowFeedSelector()
        {
            if (!(selector.DataContext is FeedSelectionVM))
            {
                selector.DataContext = new FeedSelectionVM(selector.feedsByCat);
            }

            ((FeedSelectionVM)selector.DataContext).ResetSelection();
            ((FeedSelectionVM) selector.DataContext).FeedSelectionCompleted += selectorVM_HideRequested;
            showSelectorStory.Begin();
        }

        private void selectorVM_HideRequested(object sender, System.EventArgs e)
        {
            HideFeedSelector();
        }

        private void HideFeedSelector()
        {
            FeedSelectionVM vm = selector.DataContext as FeedSelectionVM;
            if (vm == null)
                return;

            vm.FeedSelectionCompleted -= selectorVM_HideRequested;
            hideSelectorStory.Begin();

            if (vm.SelectionAdded || vm.SelectionRemoved)
            {
                ((FeedViewModel)DataContext).Begin(vm.SelectionRemoved).ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        Logger.Log.ErrorFormat("HideFeedSelector() failed. Exception {}", t.Exception);
                    }

                });
            }
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var vm = ViewModel;
            if (vm == null)
            {
                vm = new FeedViewModel();
                ViewModel = vm;
                vm.Begin(e.Parameter is bool && (bool)e.Parameter).ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        Logger.Log.ErrorFormat("Begin() failed. Exception {0}", t.Exception);
                    }
                });
            }

            PersistenceHelper.GetUserFeedsAsync().AsTask().ContinueWith( async t => 
                {
                    var userFeeds = t.Result;
                    if (userFeeds.Count() == 0)
                    {
                      await  this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,  () => ShowFeedSelector());
                    }
                }, TaskScheduler.Current);
        }

        private void HandleReloadClick(object sender, RoutedEventArgs e)
        {
            var vm = ViewModel;
            if (vm != null)
            {
                vm.ReloadFromInternet();
            }
        }

        private void HandleAppBarOpened(object sender, object e)
        {
            portrait.ClosePopup();
        }
    }
}